﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using lite;
using Csla;
using Csla.Data;
using Csla.Core;
using System.Collections.ObjectModel;
using OpenExpressApp.ORM;
using OpenExpressApp.MetaAttribute;
using OpenExpressApp.DB.Utils;
using System.Diagnostics;
using OpenExpressApp.Types;


namespace OpenExpressApp.Module.Library
{
    [Serializable]
    public partial class OrgPositions : GBusinessListBase<OrgPositions, OrgPosition>
    {
        #region  Factory Methods

        internal static OrgPositions GetList(Guid userId)
        {
            return DataPortal.Fetch<OrgPositions>(userId);
        }

        private OrgPositions()
        {
            /* Require use of factory methods */
            AllowNew = true;
        }

        public static OrgPositions GetChild(Org parent)
        {
            return DataPortal.FetchChild<OrgPositions>(parent);
        }

        public static OrgPositions NewChild()
        {
            return DataPortal.CreateChild<OrgPositions>();
        }

        protected override object AddNewCore()
        {
            var item = OrgPosition.NewChild();
            this.Add(item);
            return item;
        }

        #endregion

        #region  Data Access

        private void Child_Fetch(Org parent)
        {
            RaiseListChangedEvents = false;

            using (var db = DBHelper.CreateDb(ConnectionStringNames.OpenExpressApp))
            {
                IQuery q = db.Query();
                q.Constrain("OrgId").Equal(parent.Id);
                foreach (OrgPosition c in db.Select<OrgPosition>(q))
                {
                    this.Add(OrgPosition.GetChild(parent, c));
                }
            }

            RaiseListChangedEvents = true;
        }

        private void DataPortal_Fetch(Guid userId)
        {
            RaiseListChangedEvents = false;

            using (var db = DBHelper.CreateDb(ConnectionStringNames.OpenExpressApp))
            {
                IQuery q = db.Query().Constrain("UserId").Equal(userId);

                var positionIds = db.Select<OrgPositionUser>(q).Select(pu => pu.OrgPositionId).ToList();

                q = db.Query().Constrain("Id").In(positionIds);

                foreach (OrgPosition c in db.Select<OrgPosition>(q))
                {
                    var position = DataPortal.FetchChild<OrgPosition>(c);
                    this.Add(position);
                }
            }

            RaiseListChangedEvents = true;
        }

        #endregion
    }


    [Serializable]
    [Table]
    [BusinessObject("C5749CC3-1BE1-4E8F-9E2F-01CFD9729FDC", Direction = Direction.Horizontal), Label("岗位")]
    [NotAllowNew, NotAllowEdit]
    public partial class OrgPosition : GBusinessBase<OrgPosition>
    {
        #region  Business Methods

        private static PropertyInfo<Guid> IdProperty =
            RegisterProperty(new PropertyInfo<Guid>("Id"));
        [System.ComponentModel.DataObjectField(true, true)]
        [Column, PK]
        [EntityProperty]
        public Guid Id
        {
            get { return GetProperty(IdProperty); }
            set { SetProperty(IdProperty, value); }
        }

        private static PropertyInfo<Guid> OrgIdProperty =
         RegisterProperty(new PropertyInfo<Guid>("OrgId"));
        [Column]
        [EntityProperty]
        [Lookup("Org")]
        public Guid OrgId
        {
            get { return GetProperty(OrgIdProperty); }
            set { SetProperty(OrgIdProperty, value); }
        }
        [NotUndoable()]
        private Org org;
        public Org Org
        {
            get { return org; }
            set
            {
                org = value;
                PropertyHasChanged("Org");
            }
        }

        private static PropertyInfo<Guid> PositionIdProperty =
 RegisterProperty(new PropertyInfo<Guid>("PositionId"));
        [Column]
        [EntityProperty]
        [Label("岗位")]
        [Lookup("Position", UseSelectAddCommand = true)]
        public Guid PositionId
        {
            get { return GetProperty(PositionIdProperty); }
            set { SetProperty(PositionIdProperty, value); }
        }

        [NotUndoable()]
        private Position _position;
        public Position Position
        {
            get { return _position; }
            set
            {
                _position = value;
                PropertyHasChanged("Position");
                PropertyHasChanged("Code");
                PropertyHasChanged("Name");
                PropertyHasChanged("UseTime");
                PropertyHasChanged("CycleType");
                PropertyHasChanged("LoginTotalCount");
            }
        }

        [EntityProperty, ShowInList, Label("编码")]
        public string Code
        {
            get { return _position.Code; }
        }

        [EntityProperty, ShowInList, Label("名称")]
        public string Name
        {
            get { return _position.Name; }
        }

        //[EntityProperty, ShowInList, Label("使用时间(小时/次)")]
        //public double UseTime
        //{
        //    get { return _position.UseTime; }
        //}

        [EntityProperty, ShowInList, Label("使用时间(分钟/次)")]
        public int UseTime
        {
            get { return (int)_position.UseTime * 60; }
        }

        [EntityProperty, ShowInList, Label("使用周期)")]
        public CycleType CycleType
        {
            get { return _position.CycleType; }
        }

        [EntityProperty, ShowInList, Label("使用次数")]
        public int LoginTotalCount
        {
            get { return _position.LoginTotalCount; }
        }

        private static PropertyInfo<OrgPositionUsers> OrgPositionUsersProperty =
            RegisterProperty(new PropertyInfo<OrgPositionUsers>("OrgPositionUsers"));
        [Association]
        public OrgPositionUsers OrgPositionUsers
        {
            get
            {
                if (!FieldManager.FieldExists(OrgPositionUsersProperty))
                {
                    LoadProperty(OrgPositionUsersProperty, OrgPositionUsers.NewChild());
                }
                return GetProperty(OrgPositionUsersProperty);
            }
        }

        private static PropertyInfo<OrgPositionOperations> OrgPositionOperationsProperty =
            RegisterProperty(new PropertyInfo<OrgPositionOperations>("OrgPositionOperations"));
        [Association(AssociationOperateType = AssociationOperateType.Selected)]
        public OrgPositionOperations OrgPositionOperations
        {
            get
            {
                if (!FieldManager.FieldExists(OrgPositionOperationsProperty))
                {
                    LoadProperty(OrgPositionOperationsProperty, OrgPositionOperations.NewChild());
                }
                return GetProperty(OrgPositionOperationsProperty);
            }
        }

        private static PropertyInfo<OrgPositionDataPermissions> OrgPositionDataPermissionsProperty =
            RegisterProperty(new PropertyInfo<OrgPositionDataPermissions>("OrgPositionDataPermissions"));
        [Association]
        public OrgPositionDataPermissions OrgPositionDataPermissions
        {
            get
            {
                if (!FieldManager.FieldExists(OrgPositionDataPermissionsProperty))
                {
                    if (IsNew)
                    {
                        LoadProperty(OrgPositionDataPermissionsProperty, OrgPositionDataPermissions.NewChild());
                    }
                    else
                    {
                        LoadProperty(OrgPositionDataPermissionsProperty, OrgPositionDataPermissions.GetChild(this));
                    }
                }

                return GetProperty(OrgPositionDataPermissionsProperty);
            }
        }

        #endregion

        #region  Factory Methods

        public static OrgPosition NewChild()
        {
            return DataPortal.CreateChild<OrgPosition>();
        }

        public static OrgPosition GetChild(Org org, OrgPosition c)
        {
            c.Org = org;
            return DataPortal.FetchChild<OrgPosition>(c);
        }

        private OrgPosition()
        {
            /* require use of factory methods */
        }


        #endregion

        #region  Data Access

        protected override void Child_Create()
        {
            LoadProperty(IdProperty, Guid.NewGuid());
            ValidationRules.CheckRules();
        }

        private void Child_Fetch(OrgPosition data)
        {
            LoadProperty(IdProperty, data.ReadProperty(IdProperty));
            LoadProperty(OrgIdProperty, data.ReadProperty(OrgIdProperty));
            LoadProperty(OrgPositionUsersProperty, OrgPositionUsers.GetChild(this));
            LoadProperty(OrgPositionOperationsProperty, OrgPositionOperations.GetChild(this));
            Debug.Assert(null != data.PositionId);
            LoadProperty(PositionIdProperty, data.PositionId);
            _position = Position.GetLazy((Guid)data.PositionId);
        }

        private void Child_Insert(BusinessBase parent)
        {
            using (var db = DBHelper.CreateDb(ConnectionStringNames.OpenExpressApp))
            {
                db.Insert(this);
                FieldManager.UpdateChildren(this);
            }
        }

        private void Child_Update(BusinessBase parent)
        {
            using (var db = DBHelper.CreateDb(ConnectionStringNames.OpenExpressApp))
            {
                db.Update(this);
                FieldManager.UpdateChildren(this);
            }
        }

        private void Child_DeleteSelf(BusinessBase parent)
        {
            using (var db = DBHelper.CreateDb(ConnectionStringNames.OpenExpressApp))
            {
                db.Delete(this);
                FieldManager.UpdateChildren(this);
            }
        }

        #endregion

        #region  Validation Rules

        protected override void AddBusinessRules()
        {

        }

        #endregion
    }
}